//
//  JCCMoneyViewController.swift
//  剂查查
//
//  Created by shoubin tao on 2024/12/3.
//  Copyright © 2024 shipin. All rights reserved.
//

import CommonTools
import UIKit
import TYUIKit
import TYAlertView

class JCCErrorModifyViewController: BaseViewController {
    
    @IBOutlet private weak var iconIv: UIImageView!
    
    @IBOutlet private weak var nameLabel: UILabel!
    
    @IBOutlet private weak var companyLabel: UILabel!
    
    @IBOutlet private weak var infoLabel: UILabel!
    
    @IBOutlet private weak var bottomBtn: UIButton!
    
    @IBOutlet weak var typeView: UIView!
    
    @IBOutlet weak var feedbackTypeLabel: UILabel!
    
    @IBOutlet weak var moreIv: UIImageView!
    
    @IBOutlet private weak var textView: TYTextView!
    
    @IBOutlet private weak var pickImageView: UIView!
    
    var choosedImages: [UIImage] = []
    
    var infoModel: JCCScanResultInfoModel =  JCCScanResultInfoModel(dict: [:])
    
    var typeList: [String] = []
    
    var currentType: String = ""
    
    override func viewWillAppear(_ animated: Bool) {
//        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        self.navigationController?.navigationBar.standardAppearance.backgroundColor = .white
//        view.backgroundColor = UIColor(hex: "#F0F4F9")
        self.bottomBtn.layer.cornerRadius = 27.5
        self.bottomBtn.clipsToBounds = true
        
        setTitle("纠错")
        
        showInfo()
        
        moreIv.image = UIImage(nameInBundle: .commonTools("app_back_black"))?.byRotate180()?.byResize(to: CGSize(width: 12, height: 11))
        typeView.addTapGesture {[unowned self] tap in
            if typeList.isEmpty {
                loadTypeList { [unowned self] in
                    chooseType()
                }
            }
            else{
                chooseType()
            }
        }
        
        textView.placeholder = "请输入"
        
        loadTypeList()
        
        bottomBtn.addBlock(for: .touchUpInside) {[unowned self] _ in
            upload()
        }
        
        let pickerView = PickerImageView(backgroundColor: .white, in: pickImageView) { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        pickerView.callback = {[unowned self] images in
            choosedImages = images
        }
    }
    
    
    func showInfo() {
        nameLabel.text = infoModel.name
        companyLabel.text = infoModel.grade_title
        iconIv.setImageUrl(url: infoModel.data_image)
        infoLabel.text = infoModel.data_specs
    }
    
    func chooseType() {
        TYAlertView.showCommonAlert(message: nil, style: .actionSheet, buttonTitles: typeList, cancelButtonTitle: "取消") {[self] alert, index in
            currentType = typeList[index - 1]
            feedbackTypeLabel.text = currentType
        }
    }
    
    func loadTypeList(callback: (() -> ())? = nil) {
        NetworkRequest.request(networkType: .feedbackCate) { result in
            switch result {
            case .success(let response):
                guard let response = response as? [String] else {return}
                self.typeList = response
                callback?()
                XWLog(value: "获取到反馈分类列表: \(response)")
            case .failure(let error):
                XWLog(value: "获取反馈分类列表失败")
            }
        }
    }
    
    func upload() {
        if currentType == "" {
            toast(message: "请选择纠错类型")
            return
        }
        let content = textView.text ?? ""
        if content == "" {
            toast(message: "请输入纠错信息")
            return
        }
        if choosedImages.isEmpty {
            toast(message: "请选择图片")
            return
        }
        
        let uploadErrorInfo: (String?) -> () = {[weak self] image in
            guard let self = self else {return}
            NetworkRequest.request(networkType: .feedback(gcode: infoModel.code, content_img: image ?? "", content: content, cate_name: currentType)) { result in
                hideLoading()
                switch result {
                case .success(let response):
                    XWLog(value: "纠错成功")
                    toast(message: "感谢您的支持，我们会尽快跟进")
                    self.navigationController?.popViewController(animated: true)
                case .failure(let error):
                    XWLog(value: "纠错失败：\(error)")
                }
            }
        }
        showLoading()
        if choosedImages.isEmpty {
            uploadErrorInfo(nil)
        }
        else {
            var count = 0
            var imageArr: [String] = []
            for image in choosedImages {
                JCCNet.uploadImage(image: image) {[weak self] model, error in
                    guard let self = self else {return}
                    count += 1
                    if let model = model {
                        XWLog(value: "图片上传成功:\(model.result)")
                        if model.isSuccess {
                            if let dic = model.result as? [String: Any], let url = dic["url"] as? String {
                                imageArr.append(url)
                            }
                        }
                        else {
                            toast(message: "图片上传失败")
                        }
                    }
                    else {
                        hideLoading()
                        XWLog(value: "图片上传失败")
                        toast(message: "图片上传失败")
                    }
                    if count == choosedImages.count {
                        uploadErrorInfo(imageArr.joined(separator: ","))
                    }
                }
            }
        }
        
    }
    
    
    
}
